<?php

//require_once("member.class.php");
//require_once("basket.class.php");
//require_once("product.class.php");

class producer extends Model
{
	//data members which correspond to database values for attributes of a producer

	var $name = 'Producer';
	var $primaryKey = 'producer_id';
	var $belongsTo = array('Member');
	var $hasMany = array(
		'Product' => array(
			'order' => 'Product.product_name'
		)
	);
	
	/***
	* Recommends an untaken producer ID based on the business name input
	*/
	function recommendProducerID($businessName) {
		$rec = preg_replace('/[a-z\s\W]/','',$businessName);
		$n = 1;
		do {
			$l = 5 - strlen($n);
			if(strlen($rec)>$l) {
				$rec = substr($rec,0,$l) . $n;
			} else {
				$rec = str_pad($rec,$l,'0') . $n;
			}
			$n++;
		} while ($this->idExists($rec));
		return $rec;
	}
	
	function idExists($id) {
		$found = $this->find($this->primaryKey . ' = "' . $id . '"');
		if (!empty($found)) {
			return true;
		} else {
			return false;
		}
	}
	
	function findProducersWithInvoices($del = null) {
		$d = ($del === null) ? Configure::read('Delivery.delivery_id') : $del;
		$sql = 'SELECT DISTINCT Producer.producer_id, Member.business_name, Member.address_line1, Member.address_line2, Member.city, Member.state, Member.zip, Member.work_address_line1, Member.work_address_line2, Member.work_city, Member.work_state, Member.work_zip FROM producers as Producer, members as Member, basket_items as Basket, product_list as Product, orderables as Orderable
		WHERE Member.member_id = Producer.member_id
		AND Product.producer_id = Producer.producer_id
		AND Orderable.product_id = Product.product_id
		AND Orderable.id = Basket.orderable_id
		AND Orderable.delivery_id = ' . $d;
		
		$r = $this->query($sql);
		return $r;
	}
	
	function formatAddresses($producers) {
		$r = array();
		foreach($producers as $producer) {
			$a = array();
			$a[] = $producer['Member']['business_name'];
			$w = (!empty($producer['Member']['work_address_line1'])) ? 'work_' : '';
			$a[] = $producer['Member'][$w . 'address_line1'];
			if (!empty($producer['Member'][$w . 'address_line2'])) {
				$a[] = $producer['Member'][$w . 'address_line2'];
			}
			$a[] = $producer['Member'][$w . 'city'] . ', ' . $producer['Member'][$w . 'state'] . ' ' . $producer['Member'][$w . 'zip'];
			$r[] = $a;
		}
		return $r;
	}
	
}

?>
